﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Transactions;
using System.Web.Mvc;
using ZBJF.Warranty.BLL;
using ZBJF.Warranty.Common.Common;
using ZBJF.Warranty.Common.Enums.InsuranceWarranty;
using ZBJF.Warranty.Common.Enums.System;
using ZBJF.Warranty.Model;
using ZBJF.Warranty.Model.ViewModel.InsuranceWarranty;
using ZBJF.Warranty.WebProvider;

namespace ZBJF.Warranty.AdminSite.Controllers
{
    public class AuditProjectConfigurationController : BaseController
    {

        #region 信息审核配置页面 + ActionResult AuditProjectConfigurationIndex()
        public ActionResult AuditProjectConfigurationIndex()
        {
            return View();
        }
        #endregion

        #region 信息审核配置管理页面获取列表数据 + ActionResult AuditProjectConfigurationList(AuditProjectConfigurationModel model)
        /// <summary>
        /// 信息审核配置管理页面获取列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult AuditProjectConfigurationList(AuditProjectConfigurationModel model)
        {
            var total = 0;
            var list = ServiceFactory.AuditProjectConfigurationServiceInstance.GetPagingList(model, out total).AsNoTracking().ToList()
                        .Select(a => new
                        {
                            a.ID,
                            a.ProjectName,
                            a.AuditProjectWithType,
                            AuditProjectType = EnumHelper.Instance.GetDescription(typeof(AuditProjectType), a.AuditProjectWithType),
                            a.FieldType,
                            FieldTypeName = EnumHelper.Instance.GetDescription(typeof(FieldTypeEnum), a.FieldType),
                            a.IsAvailable,
                            a.LastModifyBy,
                            a.LastModifyTime
                        });
            return Json(new
            {
                sEcho = model.sEcho,
                iTotalRecords = total,
                iTotalDisplayRecords = total,
                aaData = list
            }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 信息审核配置编辑 + ActionResult AuditProjectConfigurationEdit(int id)
        /// <summary>
        /// 信息审核配置编辑
        /// </summary>
        /// <returns></returns>
        public ActionResult AuditProjectConfigurationEdit(int id)
        {
            ViewBag.ShowTitle = id > 0 ? "编辑信息审核配置" : "添加信息审核配置";
            var AuditProjectConfiguration = ServiceFactory.AuditProjectConfigurationServiceInstance.LoadByID(id);
            if (AuditProjectConfiguration == null)
                AuditProjectConfiguration = new AuditProjectConfiguration();

            if (AuditProjectConfiguration.AuditProjectFieldOption == null)
                AuditProjectConfiguration.AuditProjectFieldOption = new List<AuditProjectFieldOption> { new AuditProjectFieldOption() };
            else if (AuditProjectConfiguration.AuditProjectFieldOption.Count < 1)
                AuditProjectConfiguration.AuditProjectFieldOption.Add(new AuditProjectFieldOption());

            return View(AuditProjectConfiguration);
        }

        #endregion

        #region 保存信息审核配置 + ActionResult SaveAuditProjectConfiguration(AuditProjectConfiguration model)

        [HttpPost]
        [ValidateInput(false)]
        //保存信息审核配置
        public ActionResult SaveAuditProjectConfiguration(AuditProjectConfiguration model)
        {
            var responseResult = new ResponseResult
            {
                OpreateType = model.ID > 0 ? OpreateType.Update : OpreateType.Add
            };

            var serv = ServiceFactory.AuditProjectConfigurationServiceInstance;
            model.ProjectName = model.ProjectName.Trim();
            //新增
            if (model.ID == 0)
            {
                if (serv.IsExist(model.AuditProjectWithType, model.ProjectName))
                    responseResult.Message = "该信息审核配置已经存在";
                else
                    responseResult.Success = AddAuditProjectConfiguration(model);
            }
            //修改
            else
            {
                var entity = serv.LoadByID(model.ID);
                if (entity != null)
                {
                    if (serv.IsExist(model.AuditProjectWithType, model.ProjectName, model.ID))
                    {
                        responseResult.Message = "已存在同名的信息审核配置，请修改信息审核配置名称";
                    }
                    else
                    {
                        entity = ReflectHelper<AuditProjectConfiguration, AuditProjectConfiguration>.CloneT1ToT2(model, entity);
                        responseResult.Success = EditAuditProjectConfiguration(entity);
                    }
                }
                else
                {
                    responseResult.Message = "该信息审核配置不存在或已被删除";
                }
            }
            TempData["ResponseResult"] = responseResult;
            return responseResult.Success ? RedirectToAction("AuditProjectConfigurationIndex") : RedirectToAction("AuditProjectConfigurationEdit", new { id = model.ID });
        }
        //新增审核配置
        private bool AddAuditProjectConfiguration(AuditProjectConfiguration model)
        {
            var serv = ServiceFactory.AuditProjectConfigurationServiceInstance;
            model.CreateTime = DateTime.Now;
            model.CreateBy = CurrentUser.UserAccount;
            model.LastModifyBy = CurrentUser.UserAccount;
            model.LastModifyTime = DateTime.Now;

            FieldTypeEnum type = (FieldTypeEnum)model.FieldType;
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    ICollection<AuditProjectFieldOption> options = model.AuditProjectFieldOption;
                    model.AuditProjectFieldOption = null;

                    var entity = serv.AddEntities(model);
                    if (entity.ID < 1)
                    {
                        return false;
                    }
                    //单选、多选、下拉框需要保存选项
                    if (type == FieldTypeEnum.DropDownList || type == FieldTypeEnum.CheckBoxList)
                    {
                        var optionService = ServiceFactory.AuditProjectFieldOptionServiceInstance;
                        foreach (var item in options)
                        {
                            item.AuditProjectConfigurationID = entity.ID;
                            AuditProjectFieldOption option = optionService.AddEntities(item);
                            if (option.ID < 1)
                            {
                                ts.Dispose();
                                return false;
                            }
                        }
                    }
                    ts.Complete();
                    return true;
                }
                catch (Exception ex)
                {
                    ts.Dispose();
                    LogHelper.WriteLog("保存审核项目异常：" + ex.ToString(), LogType.error);
                    return false;
                }
            }
        }

        //修改审核配置
        private bool EditAuditProjectConfiguration(AuditProjectConfiguration model)
        {
            var serv = ServiceFactory.AuditProjectConfigurationServiceInstance;

            model.LastModifyBy = CurrentUser.UserAccount;
            model.LastModifyTime = DateTime.Now;


            FieldTypeEnum type = (FieldTypeEnum)model.FieldType;
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    bool temp = serv.DeleteAuditProjectOption(model.ID);
                    ICollection<AuditProjectFieldOption> options = model.AuditProjectFieldOption;
                    model.AuditProjectFieldOption = null;
                    bool result = serv.UpdateEntities(model);
                    if (!result)
                    {
                        return false;
                    }
                    var optionService = ServiceFactory.AuditProjectFieldOptionServiceInstance;
                    //单选、多选、下拉框需要保存选项
                    if (type == FieldTypeEnum.DropDownList || type == FieldTypeEnum.CheckBoxList)
                    {
                        foreach (var item in options)
                        {
                            item.AuditProjectConfigurationID = model.ID;
                            AuditProjectFieldOption option = optionService.AddEntities(item);
                            if (option.ID < 1)
                            {
                                ts.Dispose();
                                return false;
                            }
                        }
                    }
                    ts.Complete();
                    return true;
                }
                catch (Exception ex)
                {
                    ts.Dispose();
                    LogHelper.WriteLog("保存审核项目异常：" + ex.ToString(), LogType.error);
                    return false;
                }
            }
        }
        #endregion

        #region 禁用/启用信息审核配置 + JsonResult UpdateStatus(int id, bool isAvailable)
        /// <summary>
        /// 禁用/启用信息审核配置
        /// </summary>
        /// <param name="id">主键ID</param>
        /// <param name="isAvailable">启用/禁用</param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult UpdateStatus(int id, bool isAvailable)
        {
            var entity = ServiceFactory.AuditProjectConfigurationServiceInstance.LoadByID(id);
            var success = false;
            if (entity != null)
            {
                entity.IsAvailable = isAvailable;
                entity.LastModifyBy = CurrentUser.UserAccount;
                entity.LastModifyTime = DateTime.Now;
                success = ServiceFactory.AuditProjectConfigurationServiceInstance.UpdateEntities(entity);
            }
            return Json(new
            {
                success = success,
                message = success ? "修改成功" : "修改失败"
            });
        }
        #endregion
    }
}